package com.github.ghsea.framework.job.core.client;

import java.util.ArrayList;
import java.util.List;

import org.apache.curator.utils.ZKPaths;

import com.github.ghsea.framework.job.common.AbstractEndpointLocator;
import com.github.ghsea.framework.job.common.Endpoint;
import com.github.ghsea.framework.job.common.EndpointChangedListener;
import com.github.ghsea.framework.job.common.EndpointZkNodeData;
import com.github.ghsea.framework.job.common.support.ZkPath;
import com.github.ghsea.framework.job.core.JobServerBootstrap;
import com.github.ghsea.framework.zkclient.ZkClient;

public class JobClientLocator extends AbstractEndpointLocator {

	private EndpointChangedListener endpointListener;

	private ZkClient zkClient;

	private String appName;

	JobClientLocator(String appName) {
		this.appName = appName;
		init();
	}

	@Override
	protected List<Endpoint> listAll() {
		return endpointListener.all();
	}

	private void init() {
		// TODO
		zkClient = JobServerBootstrap.getZkClient();

		String jobServerPath = ZkPath.getPathOfClients();
		try {
			endpointListener = new EndpointChangedListener();
			List<String> serverPaths = zkClient.getChildrenAndWatch(ZKPaths.makePath(jobServerPath, appName),
					endpointListener);

			if (serverPaths == null || serverPaths.size() == 0) {
				return;
			}

			List<Endpoint> endpoints = new ArrayList<>(serverPaths.size());
			serverPaths.forEach(each -> {
				EndpointZkNodeData data;
				try {
					data = (EndpointZkNodeData) zkClient.getData(ZKPaths.makePath(jobServerPath, each));
					endpoints.add(Endpoint.build(each, data.getBaseAccessUrl()));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			});
			endpointListener.init(endpoints);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
